#!/bin/bash

# Return value
Ture=0
False=1

branch=`cat .git/config | grep "branch \"" | awk -F \" '{print $2}' | awk NR==1`

# Show how to use this shell
function usage()
{
    printf "usage: bash FILE.SH \033[32m[path] ...\033[0m \n"
    printf "optional arguments:\n"
    printf "\033[32m  -h, --help              search for help information\033[0m\n"
    exit $Ture
}

if [[ $# < 1 ]];then
    printf "Try 'bash [FILE.SH] --help' for more information.\n"
    exit $False
fi

src_path=`pwd`

while [ $# -gt 0 ]
do
    case $1 in
    -h|--help)
        usage
    ;;
    *)
        dir_path=$1
        cd $dir_path
        if [ $? -ne 0 ];then
            printf  "\033[31m[****** Error Path: ${dir_path} ******]\033[0m \n"
            exit $False
        else
            printf "\033[32m[****** git reset ---> `pwd` ******]\033[0m \n"
            git checkout ${branch}
            git reset --hard HEAD^
            if [ $? -ne 0 ];then
                printf  "\033[31m[****** Error reset: `pwd` ******]\033[0m \n"
                exit $False
            fi
            printf "\033[32m[****** repo sync ---> `pwd` ******]\033[0m \n"
            repo sync -c . -j4
            if [ $? -ne 0 ];then
                printf "\033[33m[****** Warning sync: `pwd` ******]\033[0m \n"
                printf "\033[32m[------ git sync: `pwd` ------]\033[0m \n"
                # git checkout .
                git clean -fd
                git pull
                if [ $? -ne 0 ];then
                    printf "\033[31m[****** Error sync: ${dir_path} ******]\033[0m \n"
                    exit $False
                fi
            fi
            cd $src_path
        fi
    ;;
    esac
    shift
done
